package behaviors;

import model.Entity;

import org.jbox2d.collision.shapes.ShapeType;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.contacts.ContactPoint;
import org.jbox2d.dynamics.contacts.ContactResult;

import controller.Global;

public class Orient extends Behavior {
	public Entity shapeData1, shapeData2;

	@Override
	public void onCollide(ContactPoint arg0) {
		shapeData1 = ((Entity) arg0.shape1.getBody().getUserData());
		shapeData2 = ((Entity) arg0.shape2.getBody().getUserData());

		// ORDER MATTERS orientation fix for player
		if (shapeData1.name.equals("player")) {
			if (arg0.shape2.getType() != ShapeType.CIRCLE_SHAPE
					&& !shapeData2.isBullet) {
				shapeData1.orient = true;
			}
			if (!shapeData2.isBullet && !shapeData2.isSensor
					&& arg0.normal.y >= -1.5 && arg0.normal.y <= -.5) {
				shapeData1.isJumping = false;
			}
		} else if (shapeData2.name.equals("player")) {
			if (arg0.shape1.getType() != ShapeType.CIRCLE_SHAPE
					&& !shapeData1.isBullet) {
				shapeData2.orient = true;
			}
			if (!shapeData1.isBullet && !shapeData1.isSensor) {
				shapeData2.isJumping = false;
			}
		}
		shapeData1.orient = true;
		shapeData2.orient = true;
	}

	@Override
	public void onRemove(ContactPoint arg0) {
		// shapeData1 = ((Entity) arg0.shape1.getBody().getUserData());
		// shapeData2 = ((Entity) arg0.shape2.getBody().getUserData());
		// shapeData1.orient = false;
		// shapeData2.orient = false;
	}

	@Override
	public void onPersist(ContactPoint arg0) {
	}

	@Override
	public void onResult(ContactResult arg0) {
	}

	@Override
	public void update(Body b) {
		super.update(b);

		if (body != null && !body.isStatic()) {

			// handle above water orientation
			if (entity.isOrientable && body.getPosition().y > Global.waterLevel) {
				if (body.getAngularVelocity() < 4
						&& body.getAngularVelocity() > -4) {
					body.setXForm(Global.player.getPosition(), 0);
					body.m_angularVelocity = 0;
				}
			}

			// handle under water orientation
			if (body.getPosition().y < Global.waterLevel) {
				((Entity) body.getUserData()).isJumping = false;
				if (entity.isOrientable) {
					float angle = MathUtils.atan2(-body.getLinearVelocity().x,
							1);
					body.setXForm(body.getPosition(), angle);
				}
			}
		}
	}

	@Override
	public void init() {
	}
}
